
package controller;

import java.io.IOException;
import java.io.StringReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import databean.Email;

import model.EmailDAO;
import model.Model;
import model.UserDAO;


public class UploadEmailXMLAction extends Action {
	
	private UserDAO  userDAO;
	private EmailDAO emailDAO;
	
    public UploadEmailXMLAction(Model model) {
    	userDAO  = model.getUserDAO();
    	emailDAO = model.getEmailDAO();
	}
    
    public String getName() { return "upload-email-xml.do"; }
    
    public void display(){
    	
    	
    }
    
	public String perform(HttpServletRequest request, HttpServletResponse response){		
		String xmlContent = request.getParameter("file");
		Email email = new Email();
		
		
		try {
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		    DocumentBuilder db = dbf.newDocumentBuilder();
		    InputSource is = new InputSource();
		    
		    
		    //reader must skip special character
		    is.setCharacterStream(new StringReader(xmlContent));
		    
			Document doc = db.parse(is);
			doc.getDocumentElement().normalize();
			
			
			Node root = doc.getDocumentElement();
			NodeList nodes = root.getChildNodes();
			
			//messageID - sample
			Node messageid = nodes.item(0);
			request.setAttribute("message_id", messageid.getTextContent());
			
			//subject
			Node subject = nodes.item(1);	
			request.setAttribute("subject",subject.getTextContent());
			String subjectStr = subject.getTextContent();
			
			//timestamp
			Node created = nodes.item(2);
			String tspStr = created.getTextContent();
			request.setAttribute("created",tspStr);
			
			//sender name & sender email
			Node from = nodes.item(3);
			NodeList fromEmail = from.getChildNodes();
			NodeList senderInfor = fromEmail.item(0).getChildNodes();
			String senderEmail = senderInfor.item(1).getTextContent();
			String senderName = senderInfor.item(0).getTextContent();
			request.setAttribute("sender_name", senderName);
			request.setAttribute("sender_email", senderEmail);			
			
			
			//recipient - to
			Node to = nodes.item(4);
			NodeList toEmail = to.getChildNodes();
			List<String> toname = new ArrayList<String>();
			List<String> toemail = new ArrayList<String>();
			String receipStr="";
			for(int i=0;i<toEmail.getLength();i++){
				NodeList toInfor = toEmail.item(i).getChildNodes();		
				toname.add(toInfor.item(0).getTextContent());
				toemail.add(toInfor.item(1).getTextContent());
				receipStr += toInfor.item(1).getTextContent()+" ";
			}
			request.setAttribute("toname", toname);
			
			//recipient - cc
			Node cc = nodes.item(5);
			NodeList ccEmail = cc.getChildNodes();
			for(int i=0;i<ccEmail.getLength();i++){
				NodeList ccInfor= ccEmail.item(i).getChildNodes();
				receipStr +=ccInfor.item(1).getTextContent()+" ";	
			}
			receipStr = receipStr.trim().replaceAll(" ", ",");
			
			//tag
			Node tag = nodes.item(6);
			request.setAttribute("tag", tag.getTextContent());
			
			//content
			Node content = nodes.item(7);
			String contentStr = content.getTextContent();
			request.setAttribute("content", contentStr);
			
			//html
			Node html = nodes.item(8);
			request.setAttribute("html", html.getTextContent());
			Node oid = nodes.item(9);
			String oidStr = oid.getTextContent();
			request.setAttribute("oid", oidStr);
			
			try {
				email.setUserID(userDAO.getUserIDByEmail(oidStr));
				email.setOutlookID(oidStr);
				email.setTimestamp(tspStr);
				email.setSubject(subjectStr);
				email.setSender(senderEmail);
				email.setRecipient(receipStr);
				
				String body = EmailDAO.stringToHTMLString(EmailDAO.html2text(html.getTextContent()));
				System.out.println(body);
				email.setBody(body);
				
				email.setStatus("New Message From Outlook!");
				email.setConversationID(EmailDAO.retrieveConversationID(email));
				emailDAO.createEmail(email);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (SAXException se) {
			se.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		
		return "upload_email.jsp";
	}
}
